'''
此文件用于测试使用马尔可夫假设预测带有正态分布噪音的sin函数值
给定任意一个时间点去预测接下来的点是什么
结果是不理想的
'''
import sys
sys.path.append("./动手学深度学习")
import torch
import matplotlib.pyplot as plt
from torch import nn
import torch.utils
import torch.utils.data
from mymodel.utils import *
T = 1000
time = torch.arange(1,T+1,dtype=torch.float32)
y = torch.sin(0.01*time) + torch.normal(0,0.2,(T,))
# plt.plot(time,y,)
plt.xlabel("time")
plt.ylabel("y")
plt.grid()
# plt.show()

'''
suppose we have 8 sequences now, we can generate our train data like below
7 = 8 - tau + 3
456'7'   8
3456     7
2345     6
1234     5
012'3'   4
'''
tau = 4 # 序列与前4个相关
train_data = torch.zeros(T-tau,tau)
for i in range(tau):
    train_data[:,i] = y[i:i+T-tau]
labels = y[tau:] # 实际上最后一组数据没有标签
batch_size = 16
train_num = 600
da = (train_data,labels.reshape(-1,1))
train_iter = torch.utils.data.TensorDataset(*da)
train_iter = torch.utils.data.DataLoader(train_iter,batch_size,shuffle=True)
# print(train_data[:2])


net =nn.Sequential( nn.Linear(4,10),nn.ReLU(),nn.Linear(10,1))
net.apply(init_weight)

loss = nn.MSELoss()
optim = torch.optim.Adam(net.parameters(),lr=0.01)

train(net,train_iter,20,optim,loss,trygpu(0),16)
train_data = train_data.to(trygpu(0))
pre = net(train_data)
pre = pre.to(torch.device("cpu"))
plt.plot(time,y,label=1)
plt.plot(time[tau:],pre.data,label=2)
plt.legend(["ori","pre"])
plt.show()

# 结果来看，似乎很准确，但是我们都是在原始数据上预测下一个点，那么如果连续预测误差很快就会累计，很快就会偏移的很离谱